package com.maomao.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author mao
 * @date 2025-06-10- 10:27
 * @descript
 */
@Configuration
@EnableCaching
public class CaffeineConfig {

    //本地缓存配置
//    private final Cache<String, String> LOCAL_CACHE =
//            Caffeine.newBuilder().initialCapacity(1024) //初始容量
//                    .maximumSize(10000L) //最大容量
//                    // 缓存 5 分钟移除
//                    .expireAfterWrite(5L, TimeUnit.MINUTES)
//                    .build();


    /**
     * 缓存管理
     * @author mao
     * @date 2025/6/10 10:27
     * @return org.springframework.cache.CacheManager
     */
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(60, TimeUnit.SECONDS)
                .maximumSize(100));
        return cacheManager;
    }

    // 多个缓存区域
//    @Bean
//    public CacheManager cacheManager() {
//        SimpleCacheManager cacheManager = new SimpleCacheManager();
//        List<CaffeineCache> caches = new ArrayList<>();
//
//        // 配置第一个缓存区域
//        Cache<Object, Object> cache1 = Caffeine.newBuilder()
//                .expireAfterWrite(60, TimeUnit.SECONDS)
//                .maximumSize(100)
//                .build();
//        caches.add(new CaffeineCache("cache1", cache1));
//
//        // 配置第二个缓存区域
//        Cache<Object, Object> cache2 = Caffeine.newBuilder()
//                .expireAfterWrite(30, TimeUnit.SECONDS)
//                .maximumSize(50)
//                .build();
//        caches.add(new CaffeineCache("cache2", cache2));
//
//        cacheManager.setCaches(caches);
//        return cacheManager;
//    }

}
